﻿/*
* hr_department.cs
*
* 功 能： N/A
* 类 名： hr_department
*
* Ver    变更日期             负责人     变更内容
* ───────────────────────────────────
* V1.0  2015-06-23 18:38:21    黄润伟    
*
* Copyright (c) 2015 www.xhdcrm.com   All rights reserved.
*┌──────────────────────────────────┐
*│　版权所有：黄润伟                      　　　　　　　　　　　　　　│
*└──────────────────────────────────┘
*/

using System.Data;
using System.Text;
using System.Web;
using XHD.Common;
using XHD.Controller;

namespace XHD.Server
{
    public class hr_department
    {
        public static BLL.hr_department dep = new BLL.hr_department();
        public static Model.hr_department model = new Model.hr_department();

        public HttpContext Context;
        public int emp_id;
        public string emp_name;
        public Model.hr_employee employee;
        public HttpRequest request;
        public string uid;


        public hr_department()
        {
        }

        public hr_department(HttpContext context)
        {
            Context = context;
            request = context.Request;

            var userinfo = new User_info();
            employee = userinfo.GetCurrentEmpInfo(context);

            emp_id = employee.ID;
            emp_name = PageValidate.InputText(employee.name, 50);
            uid = PageValidate.InputText(employee.uid, 50);
        }

        public string deptree()
        {
            DataSet ds = dep.GetList(0, "", "d_order");
            var str = new StringBuilder();
            str.Append("[");
            str.Append("{id:0,text:'无',d_icon:''},");
            str.Append(GetTreeString(0, ds.Tables[0], null));
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }

        //public string treegrid()
        //{
        //    DataSet ds = dep.GetAllList();
        //    string dt = "{Rows:[" + GetTasksString(0, ds.Tables[0]) + "]}";
        //    context.Response.Write(dt);
        //}
        public string tree()
        {
            string serchtxt = " 1=1 ";

            string authtxt = PageValidate.InputText(request["auth"], 50);
            if (!string.IsNullOrEmpty(authtxt))
            {
                var dataauth = new GetDataAuth();
                string txt = dataauth.GetDataAuthByid(authtxt, "Sys_view", emp_id);
                string[] arr = txt.Split(':');
                switch (arr[0])
                {
                    case "my":
                    case "dep":
                        string did = employee.d_id.ToString();
                        if (string.IsNullOrEmpty(did))
                            did = "0";
                        authtxt = did;
                        break;
                    case "all":
                        authtxt = "0";
                        break;
                    case "depall":
                        DataSet dsdep = dep.GetAllList();
                        string deptask = GetTasks.GetDepTask(int.Parse(arr[1]), dsdep.Tables[0]);
                        string intext = arr[1] + "," + deptask;
                        authtxt = intext.TrimEnd(',');
                        break;
                }
            }
            //context.Response.Write(authtxt);
            DataSet ds = dep.GetList(0, serchtxt, " d_order");
            var str = new StringBuilder();
            str.Append("[");
            str.Append(GetTreeString(0, ds.Tables[0], authtxt));
            str.Replace(",", "", str.Length - 1, 1);
            str.Append("]");
            return str.ToString();
        }

        //Form JSON
        public string form(int id)
        {
            DataSet ds = dep.GetList("id=" + id);

            string dt = DataToJson.DataToJSON(ds);

            return dt;
        }

        //save
        public void save()
        {
            string parentid; //= string.IsNullOrEmpty(request["T_parent"]) ? "0" : request["T_parentid"];
            if (string.IsNullOrEmpty(request["T_parent_val"]) || request["T_parent_val"] == "null")
            {
                parentid = "0";
            }
            else
            {
                parentid = request["T_parent_val"];
            }

            model.d_name = PageValidate.InputText(request["T_depname"], 255);
            model.parentid = int.Parse(parentid);
            model.d_type = PageValidate.InputText(request["T_deptype"], 250);
            model.d_order = int.Parse(request["T_sort"]);
            model.d_fuzeren = PageValidate.InputText(request["T_leader"], 255);
            model.d_tel = PageValidate.InputText(request["T_tel"], 255);
            model.d_email = PageValidate.InputText(request["T_email"], 255);
            model.d_fax = PageValidate.InputText(request["T_fax"], 255);
            model.d_add = PageValidate.InputText(request["T_add"], 255);
            model.d_miaoshu = PageValidate.InputText(request["T_descript"], 255);

            if (model.d_type == "部门")
                model.d_icon = "images/icon/88.png";
            else
                model.d_icon = "images/icon/61.png";

            string id = request["id"];

            if (!string.IsNullOrEmpty(id) && id != "null")
            {
                model.id = int.Parse(id);
                DataSet ds = dep.GetList("id=" + int.Parse(id));
                DataRow dr = ds.Tables[0].Rows[0];
                dep.Update(model);

                //日志
                var log = new sys_log();

                int UserID = emp_id;
                string UserName = emp_name;
                string IPStreet = request.UserHostAddress;
                string EventTitle = model.d_name;
                string EventType = "组织架构修改";
                int EventID = model.id;
                string Log_Content = null;

                if (dr["d_name"].ToString() != request["T_depname"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "机构名称", dr["d_name"], request["T_depname"]);

                if (dr["parentname"].ToString() != request["T_parent"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "上级机构", dr["parentname"], request["T_parent"]);

                if (dr["d_type"].ToString() != request["T_deptype"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "机构类型", dr["d_type"], request["T_deptype"]);

                if (dr["d_order"].ToString() != request["T_sort"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "部门排序", dr["d_order"], request["T_sort"]);

                if (dr["d_fuzeren"].ToString() != request["T_leader"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "负责人", dr["d_fuzeren"], request["T_leader"]);

                if (dr["d_tel"].ToString() != request["T_tel"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "电话", dr["d_tel"], request["T_tel"]);

                if (dr["d_email"].ToString() != request["T_email"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "邮箱", dr["d_email"], request["T_email"]);

                if (dr["d_fax"].ToString() != request["T_fax"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "传真", dr["d_fax"], request["T_fax"]);

                if (dr["d_add"].ToString() != request["T_add"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "地址", dr["d_add"], request["T_add"]);

                if (dr["d_miaoshu"].ToString() != request["T_descript"])
                    Log_Content += string.Format("【{0}】{1} → {2} \n", "描述", dr["d_miaoshu"], request["T_descript"]);

                if (!string.IsNullOrEmpty(Log_Content))
                    log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, Log_Content);
            }
            else
            {
                model.isDelete = 0;
                dep.Add(model);
            }
        }

        //del
        public string del(int id)
        {
            string EventType = "组织架构删除";

            var emp = new BLL.hr_employee();
            DataSet ds = emp.GetList("d_id = " + id);

            var post = new BLL.hr_post();
            if (id == 1)
            {
                //根目录不能删除
                return ("false:first");
            }
            if (post.GetList("dep_id=" + id).Tables[0].Rows.Count > 0)
            {
                //含有岗位信息不能删除
                return ("false:post");
            }
            if (emp.GetList("d_id=" + id).Tables[0].Rows.Count > 0)
            {
                //含有员工信息不能删除
                return ("false:emp");
            }
            bool isdel = dep.Delete(id);
            if (isdel)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    int UserID = emp_id;
                    string UserName = emp_name;
                    string IPStreet = request.UserHostAddress;
                    int EventID = id;
                    string EventTitle = ds.Tables[0].Rows[i]["d_name"].ToString();
                    var log = new sys_log();
                    log.Add_log(UserID, UserName, IPStreet, EventTitle, EventType, EventID, null);
                }
                return ("true");
            }
            return ("false");
        }

        private static string GetTreeString(int Id, DataTable table, string authtxt)
        {
            DataRow[] rows = table.Select(string.Format("parentid={0}", Id));

            if (rows.Length == 0) return string.Empty;
            ;
            var str = new StringBuilder();

            foreach (DataRow row in rows)
            {
                string d_icon = "../" + (string) row["d_icon"];

                if (!string.IsNullOrEmpty(authtxt) && authtxt.IndexOf(row["id"].ToString()) == -1 && authtxt != "0")
                    d_icon = "../images/icon/50.png";

                str.Append("{id:" + (int) row["id"] + ",text:'" + row["d_name"] + "',d_icon:'" + d_icon + "'");

                if (GetTreeString((int) row["id"], table, authtxt).Length > 0)
                {
                    str.Append(",children:[");
                    str.Append(GetTreeString((int) row["id"], table, authtxt));
                    str.Append("]},");
                }
                else
                {
                    str.Append("},");
                }
            }
            return str[str.Length - 1] == ',' ? str.ToString(0, str.Length - 1) : str.ToString();
        }
    }
}